package com.hsnn.medstgmini.base.dict.controller;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.base.dict.model.DicPackunit;
import com.hsnn.medstgmini.base.dict.service.DicPackunitManager;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.util.Pagination;
import com.hsnn.medstgmini.util.ParseDate;

/**
 * @category 包装单位字典
 * @author 王炳
 * @date 2015年7月27日
 */
@Controller
@RequestMapping("/dicPackunit")
public class DicPackunitController {
	
	private static final Logger log = Logger.getLogger(DicPackunitController.class);

	@Autowired
	private DicPackunitManager dicPackunitManager;
	
	@Autowired
	private HttpServletRequest request;
	
	/**
	 * 
	 *@category 跳转包装单位字典页面
	 *@author wangbing
	 *@date 2015年7月27日
	 *String
	 */
	@RequestMapping("/toDicPackunitList")
	public String  toDicPackunitList() {
		log.info("enter toDicPackunitList method!");
		return "/base/dict/packunitList";
	}
	
	/**
	 * 
	 *@category 获取包装单位列表
	 *@author wangbing
	 *@date 2015年7月27日
	 *Pagination
	 */
	@RequestMapping("/getDicDrugspecList")
	@ResponseBody
	public Pagination getDicDrugspecList(){
		printParams();
		Pagination page =new Pagination(request);
		try{
		String packunitCode = request.getParameter("packunitCode");
		String packunitName = request.getParameter("packunitName");
		String status = request.getParameter("status");
		if(StringUtils.isNotBlank(packunitCode)){
			page.getConditions().put("packunitCode", packunitCode.trim());
		}
		if(StringUtils.isNotBlank(packunitName)){
			page.getConditions().put("packunitName", packunitName.trim());
		}
		if(StringUtils.isNotBlank(status)){
			page.getConditions().put("status", status);
		}
		page = dicPackunitManager.getDicPackunitList(page);
		} catch (Exception e) {
			e.printStackTrace();
		} catch(Error error) {
			error.printStackTrace();
		}
		return page;
	}
	
	/**
	 * 
	 *@category 启用停用（包含批量）
	 *@author wangbing
	 *@date 2015年6月9日
	 *Pagination
	 */
	@RequestMapping(value={"/enable","/disable"})
	@ResponseBody
	public Pagination batchChangeStatus(String array) {
		printParams();
		Pagination page = new Pagination();
		int count = 0;
		try {
			SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
			if (array != null && !"".equals(array)) {
				Gson gson = new Gson();
				Type type = new TypeToken<List<DicPackunit>>() {
				}.getType();
				List<DicPackunit> list = gson.fromJson(array, type);
				if (list != null && list.size()>0) {
					for (DicPackunit ddt : list) {
						ddt.setUpdUser(user.getId());
						count = dicPackunitManager.changeStatus(ddt);
					}
					page.setSuccess(true);
					page.getConditions().put("count", count+"");
				}else{
					page.setSuccess(false);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
		}
		return page;
	}
	
	
	/**
	 * 
	 *@category 新增和编辑
	 *@author wangbing
	 *@date 2015年7月27日
	 *Pagination
	 */
	@RequestMapping(value={"/add","/edit"})
	@ResponseBody
	public Pagination dicPackunitAdd(DicPackunit dicPackunit) {
		printParams();
		Pagination page=new Pagination();
        try {  
        	SysUser user = (SysUser)request.getSession().getAttribute(Constants.USERINFO);
        	dicPackunit.setUpdUser(user.getId());
        	dicPackunit.setUpdDatetime(ParseDate.parseFullFormat(new Date()));
        	String packunitId = dicPackunit.getPackunitId();
        	String packunitCode=dicPackunit.getPackunitCode();
        	String packunitName=dicPackunit.getPackunitName();
        	if(StringUtils.isBlank(dicPackunit.getStatus())){
        		dicPackunit.setStatus("1");
        	}
        	
            if(StringUtils.isNotBlank(packunitCode)){
                List<DicPackunit> list=dicPackunitManager.getPackunitBy("packunitCode",packunitCode,packunitId);
            	if(list.size()>0){
            	    page.setMsg("包装单位编码已存在!");
            	    page.setSuccess(false);
            	    return page;
                }
            }else{
            	page.setMsg("请输入包装单位编码!");
            	page.setSuccess(false);
            	return page;
            }
            if(StringUtils.isNotBlank(packunitName)){
            	List<DicPackunit> list=dicPackunitManager.getPackunitBy("packunitName",packunitName,packunitId);
            	 if(list.size()>0){
            		 page.setMsg("包装单位已存在!");
            		 page.setSuccess(false);
            		 return page;
                 }
            }else{
            	page.setMsg("请输入包装单位!");
            	page.setSuccess(false);
            	return page;
            }
            if(StringUtils.isBlank(packunitId)){
        		dicPackunit.setPackunitId(null);
        	}
            page.getConditions().put("packunitId", packunitId);
            page.getConditions().put("packunitName", packunitName);
            page.getConditions().put("packunitCode", packunitCode);
			page.getConditions().put("updUser", user.getId());
    		dicPackunitManager.addAndEdit(page);
    		page.setMsg("操作成功!");
    		page.setSuccess(true);
        } catch (Exception e) {  
            e.printStackTrace(); 
            page.setMsg("操作失败!");
            page.setSuccess(false);
        }
		return page; 
	}
	
	/**
	 * 
	 *@category 获取参数打印
	 *@author 徐国鹏
	 *@date 2015年6月9日
	 *Pagination
	 */
	@SuppressWarnings("rawtypes")
	public void printParams(){
		Enumeration paramNames = request.getParameterNames();
		try {
			while (paramNames.hasMoreElements()) {
				String paramName = (String) paramNames.nextElement();
				String paramValue = request.getParameter(paramName);
				log.info(paramName+":"+paramValue);
			}
		} catch (Exception e) {
			log.error("",e);
		}
	}
	
	@RequestMapping("exportExcel")
	@ResponseBody
	public Pagination exportExcel(HttpServletResponse response){
		printParams();
		Pagination page = new Pagination();
		String packunitCode = request.getParameter("packunitCode");
		String packunitName = request.getParameter("packunitName");
		String status = request.getParameter("status");
		if(StringUtils.isNotBlank(packunitCode)){
			page.getConditions().put("packunitCode", packunitCode.trim());
		}
		if(StringUtils.isNotBlank(packunitName)){
			page.getConditions().put("packunitName", packunitName.trim());
		}
		if(StringUtils.isNotBlank(status)){
			page.getConditions().put("status", status.trim());
		}
		try {
			response.addHeader("Content-Disposition", "attachment;filename="+new String("包装单位.xls".getBytes("GB2312"),"iso8859-1")); 
			OutputStream os= new BufferedOutputStream(response.getOutputStream());  
			 response.setContentType("application/vnd.ms-excel;charset=utf-8");  
			dicPackunitManager.exportExcel(page,os);
		} catch (Exception e) {
			page.setSuccess(false);
			e.printStackTrace();
		}
		return page;
	}
}
